<template>
  <tl-sub-page :render="render" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" width="1200px" @open="open" @close="close">
    <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="120px" :disabled="disableEditSubmit || disableSave">
      <el-row style="margin-top:0px">
        <el-col :span="24">
          <el-divider content-position="left"><span>1、【项目】相关信息</span></el-divider>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="项目名称">
            <el-input v-model="model.dispprojectid" :disabled="true"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目编号">
            <el-input v-model="model.projectcode" :disabled="true"> </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="计划开工日期">
            <el-date-picker v-model="model.planstarttime" type="date" value-format="yyyy-MM-dd" placeholder="计划开工日期" disabled></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划完工日期">
            <el-date-picker v-model="model.planendtime" type="date" value-format="yyyy-MM-dd" placeholder="计划完工日期" disabled></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-divider content-position="left"><span>2、【任务】相关信息</span></el-divider>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="里程碑" prop="milepostid" :required="true" :rules="rules.validateRequire">
            <el-input v-model="model.dispmilepostid" :disabled="true" class="tl-ref-selector">
              <el-button slot="append" type="primary" icon="el-icon-search" @click="openpmMilepostRefDialog" v-if="!disableEditSubmit && !disableSave"></el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务名称" prop="name" :rules="rules.validateRequire">
            <el-input v-model="model.name"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="任务类型" prop="tasktype" :rules="rules.validateRequire">
            <el-select v-model="model.tasktype" filterable clearable>
              <el-option v-for="item in codeModel.tasktypeList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="优先级" prop="priority" :rules="rules.validateRequire">
            <el-select v-model="model.priority" filterable clearable>
              <el-option v-for="item in codeModel.priorityList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="任务类别" prop="taskcategory" :rules="rules.validateRequire">
            <el-select v-model="model.taskcategory" filterable clearable @change="currentTaskState">
              <el-option v-for="item in codeModel.taskcategoryList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务状态" prop="taskstate">
            <el-select v-model="model.taskstate" filterable clearable disabled>
              <el-option v-for="item in codeModel.taskstateList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="负责人" prop="leadername" :required="true" :rules="rules.validateRequire">
            <el-input v-model="model.leadername" :disabled="true" class="tl-ref-selector">
              <el-button slot="append" type="primary" icon="el-icon-search" @click="openpmTeamRefDialog" v-if="!disableEditSubmit && !disableSave"></el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人工号" prop="leadercode">
            <el-input v-model="model.leadercode" :readonly="true" class="is-disabled"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="参与人" prop="participantnames">
            <el-input v-model="model.participantnames" :disabled="true" class="tl-ref-selector">
              <el-button slot="append" type="primary" icon="el-icon-search" @click="openpmTeamParticipantRefDialog" v-if="!disableEditSubmit && !disableSave"></el-button>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="参与人工号" prop="participantcodes">
            <el-input v-model="model.participantcodes" :readonly="true" class="is-disabled"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="任务说明" prop="explain">
            <el-input v-model="model.explain" type="textarea" :rows="2"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="计划开始日期" prop="starttime" v-show="model.taskcategory == '1'" :rules="model.taskcategory == '1' ? rules.validateRequire : { required: false }">
            <el-date-picker v-model="model.starttime" type="date" placeholder="计划开始日期" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划结束日期" prop="endtime" v-show="model.taskcategory == '1'" :rules="model.taskcategory == '1' ? rules.validateRequire : { required: false }">
            <el-date-picker v-model="model.endtime" type="date" placeholder="计划结束日期" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="实际开始日期" prop="actualstarttime" v-show="model.taskstate == '3' || model.taskstate == '4' || model.taskcategory == '2'" :rules="model.taskcategory == '2' ? rules.validateRequire : { required: false }">
            <el-date-picker v-model="model.actualstarttime" type="date" placeholder="实际开始日期" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实际结束日期" prop="actualendtime" v-show="model.taskstate == '4' || model.taskcategory == '2'" :rules="model.taskcategory == '2' ? rules.validateRequire : { required: false }">
            <el-date-picker v-model="model.actualendtime" type="date" placeholder="实际完成日期" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" v-show="model.taskstate == '0'">
          <el-form-item label="任务取消日期" prop="canceltime">
            <el-date-picker v-model="model.canceltime" type="date" placeholder="任务取消日期" value-format="yyyy-MM-dd" :disabled="true"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" v-show="model.taskstate == '0'">
          <el-form-item label="任务取消原因" prop="cancelreason">
            <el-input v-model="model.cancelreason" type="textarea" :rows="2"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="自评进度" prop="progress" :rules="model.taskcategory == '2' ? rules.validateRequire : { required: false }">
            <el-input-number v-model="model.progress" controls-position="right" :step="10" :min="0" :max="100" style="width:95%" :disabled="model.taskcategory != '2'"></el-input-number>
            <span>%</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="进度说明" prop="progressexplain" :rules="model.taskcategory == '2' ? rules.validateRequire : { required: false }">
            <el-input v-model="model.progressexplain" type="textarea" :rows="2" :disabled="model.taskcategory != '2'"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="任务进度评分" prop="progressscore" v-show="model.taskstate == '4' && model.state == '9'">
            <el-input-number v-model="model.progressscore" controls-position="right" :step="10" :min="0" :max="100" style="width:100%" :disabled="true"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务质量评分" prop="qualityscore" v-show="model.taskstate == '4' && model.state == '9'">
            <el-input-number v-model="model.qualityscore" controls-position="right" :step="10" :min="0" :max="100" style="width:100%" :disabled="true"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="description">
            <el-input v-model="model.description" type="textarea" :rows="2"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-collapse>
        <el-collapse-item title="【单据】相关信息">
          <el-row>
            <el-col :span="12">
              <el-form-item label="派工部门" prop="deptname">
                <tl-ref-dept v-model="model.deptcode" :initDisplayData.sync="model.deptname" :disabled="true" dataType="code" nameType="fullname" :singleSelect="true" :externalQueryParam="{qry_enabled:1}"></tl-ref-dept>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="派工公司" prop="orgname">
                <el-input v-model="model.orgname" :readonly="true" class="is-disabled"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="派工人" prop="username">
                <tl-ref-user v-model="model.username" :initDisplayData.sync="model.username" :disabled="true" dataType="code" :singleSelect="true"></tl-ref-user>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="派工人工号" prop="usercode">
                <el-input v-model="model.usercode" :readonly="true" class="is-disabled"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="单据日期" prop="docdate" :rules="rules.validateRequire">
                <el-date-picker v-model="model.docdate" type="date" placeholder="单据日期" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="提交时间" prop="submitdate">
                <el-date-picker v-model="model.submitdate" type="datetime" placeholder="提交时间" disabled></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="审批流程" prop="flowid">
                <el-input v-model="model.dispflowid" :readonly="true" class="is-disabled"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="state">
                <el-input v-model="model.dispstate" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>
    </el-form>
    <tl-approval-history ref="history" sourceType="PmTask" :sourceId="model.id" />
    <div slot="footer" class="dialog-footer">
      <el-button :type="disableEditSubmit === false ? 'text' : 'primary'" @click="doCancelEdit" v-if="uiOperateState<=2">取消</el-button>
      <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading" v-if="!disableEditSubmit" :disabled="disableSave">
        <svg-icon icon-class="save" />保存
      </el-button>
      <!-- <el-button type="primary" @click="doCancelTask" :loading="cancelLoading" v-if="showCancelTaskButton" :disabled="disableCancelTaskButton">
                <svg-icon icon-class="undo" />任务取消</el-button> -->
      <tl-attachment sourceType="PmTask" :sourceId="model.id" :disabled="disableAttachmentButton" btnTitle="任务文件"></tl-attachment>
      <el-button type="primary" @click="doSubmitApproval" :loading="submitLoading" v-if="!disableEditSubmit" :disabled="disableApproval">
        <svg-icon icon-class="send" />提交审批
      </el-button>
      <el-button type="primary" @click="$refs.history.visible = true" :disabled="disableApprovalHistory">
        <svg-icon icon-class="list" />审批历史
      </el-button>
      <el-button type="primary" @click="doDelApproval" :loading="delApprovalLoading" v-if="!disableDelApproval" :disabled="disableDelApproval">
        <svg-icon icon-class="undo" />取消审批
      </el-button>
    </div>
    <!-- <tlpm-milepost-ref ref="pmMilepostRef" @confirm="getpmMilepostRefData" :isSingleSelect="true" :externalQueryParam="{qry_mileState:'0'}"></tlpm-milepost-ref> -->
    <tlpm-milepost-ref ref="pmMilepostRef" @confirm="getpmMilepostRefData" :isSingleSelect="true"></tlpm-milepost-ref>
    <!-- <tlpm-team-ref ref="pmTeamRef" @confirm="getpmTeamRefData" :isSingleSelect="true"></tlpm-team-ref> -->
    <tlpm-team-ref ref="pmTeamRef" @confirm="getpmTeamRefData" :isSingleSelect="true" :externalQueryParam="{qry_projectid:model.projectid,qry_notparticipantcodes:model.participantcodes}"></tlpm-team-ref>
    <!-- <tlpm-team-ref ref="pmTeamParticipantRef" @confirm="getpmTeamParticipantRefData" :isSingleSelect="false" :externalQueryParam="{qry_notleadercode:model.leadercode}"></tlpm-team-ref> -->
    <tlpm-team-ref ref="pmTeamParticipantRef" @confirm="getpmTeamParticipantRefData" :isSingleSelect="false" :externalQueryParam="{qry_projectid:model.projectid,qry_notleadercode:model.leadercode}"></tlpm-team-ref>
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
/** 子组件 */
import tlpmMilepostRef from '@/views/ProjectManage/pmMilepost/refList.vue'
import tlpmTeamRef from '@/views/ProjectManage/pmTeam/refList.vue'
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit],
  components: { tlpmMilepostRef, tlpmTeamRef },
  data() {
    return {
      moduleTitle: '任务管理',
      urlPrefix: '/pm/task/',
      disableAttachmentButton: true,
      url: {
        // 额外的url
        queryOrgByDeptId: '/pm/customer/queryOrgByDeptId',
        queryProjectById: '/pm/task/queryProjectById',
        cancelTaskById: '/pm/task/cancelTask'
      },
      cancelLoading: false
    }
  },
  props: {
    projectId: {
      type: [Number, String],
      default: function() {
        return ''
      }
    },
    editFlag: {
      type: Boolean,
      default: true
    }
  },
  methods: {
    assignDefaultValue() {
      if (this.isAdd) {
        // if (this.codeModel.flowidList && this.codeModel.flowidList.length > 0) {
        //     this.$set(this.model, 'flowid', parseInt(this.codeModel.flowidList[0].id))
        // }
        this.$set(this.model, 'orgcode', this.org.code)
        this.$set(this.model, 'orgname', this.org.name)
        this.$set(this.model, 'deptcode', this.dept.code)
        this.$set(this.model, 'deptname', this.dept.fullname)
        this.$set(this.model, 'usercode', this.user.code)
        this.$set(this.model, 'username', this.user.name)
        this.$set(this.model, 'docdate', new Date())
        this.$set(this.model, 'progress', 0)
        // 开立1，已发布2，进行中3，完成4，取消0。
        // if (this.codeModel.taskstateList && this.codeModel.taskstateList.length > 0) {
        // this.$set(this.model, 'taskstate', '1')
      }
    },
    afterDelApproval() {
      this.disableAttachmentButton = false
    },
    currentTaskState() {
      if (this.model.taskcategory === '1') {
        this.$set(this.model, 'taskstate', '1')
        this.$set(this.model, 'progress', '0')
        this.$set(this.model, 'progressexplain', '')
        this.$set(this.model, 'actualstarttime', '')
        this.$set(this.model, 'actualendtime', '')
      }
      if (this.model.taskcategory === '2') {
        this.$set(this.model, 'taskstate', '4')
        this.$set(this.model, 'starttime', '')
        this.$set(this.model, 'endtime', '')
      }
    },
    loaded() {
      if (this.isAdd === false && this.disableEditSubmit === true) {
        var params = {
          sourceType: 'PmTask',
          sourceId: this.model.id
        }
        this.disableAttachmentButton = false
        getAction('/cbo/attachment/calculateCount', params).then((res) => {
          if (res.success) {
            if (res.result === 0) {
              this.disableAttachmentButton = true
              this.$emit('refresh')
            }
          }
        })
      }
      // 页面加载完毕执行
      if (!this.isAdd && this.model.docno) {
        this.title = this.title + `（单据编号：${this.model.docno}）`
      }
    },
    /** 执行新增提交 */
    doAdd() {
      this.saveLoading = true
      // 增加唯一单号
      this.$set(this.model, 'billuid', this.uid)
      postAction(this.url.add, this.model)
        .then(res => {
          if (res.success) {
            this.$tap.message('添加成功', 'success')
            this.queryData(res.result.id)
            this.disableAttachmentButton = false
            this.isAdd = false
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch(err => {
          this.saveLoading = false
        })
    },
    onSelectDept(selectedDepts) {
      const selectedDept = selectedDepts[0]
      const { id, code, fullname } = selectedDept
      this.$set(this.model, 'deptcode', code)
      this.$set(this.model, 'deptname', fullname)
      const param = {
        deptId: id
      }
      getAction(this.url.queryOrgByDeptId, param).then(res => {
        if (res.success) {
          const { code: orgcode, name: orgname } = res.result
          this.$set(this.model, 'orgcode', orgcode)
          this.$set(this.model, 'orgname', orgname)
        } else {
          this.$tap.alert('已选部门关联公司信息错误，请联系系统管理员')
        }
      })
    },
    /** 打开里程碑参照 */
    openpmMilepostRefDialog() {
      this.$refs.pmMilepostRef.visible = true
    },
    /** 获取里程碑参数数据 */
    getpmMilepostRefData(selectionRow, selectKey, selectionValue) {
      this.$set(this.model, 'milepostid', selectionRow.id)
      this.$set(this.model, 'dispmilepostid', selectionRow.milepostname)
      const param = {
        projectId: selectionRow.projectid
      }
      getAction(this.url.queryProjectById, param).then(res => {
        if (res.success) {
          const { id, name, code, planstarttime, planendtime } = res.result
          this.$set(this.model, 'projectid', id)
          this.$set(this.model, 'dispprojectid', name)
          this.$set(this.model, 'projectcode', code)
          this.$set(this.model, 'planstarttime', planstarttime)
          this.$set(this.model, 'planendtime', planendtime)
        } else {
          this.$tap.alert('任务关联项目信息错误，请联系系统管理员')
        }
      })
    },
    /** 打开负责人姓名参照 */
    openpmTeamRefDialog() {
      if (!this.model.milepostid) {
        this.$message({
          message: '请先选择里程碑！',
          type: 'warning'
        })
        this.$refs.pmTeamRef.visible = false
      } else {
        this.$refs.pmTeamRef.visible = true
      }
    },
    /** 获取负责人姓名参数数据 */
    getpmTeamRefData(selectionRow, selectKey, selectionValue) {
      debugger
      this.$set(this.model, 'leadername', selectionRow.username)
      this.$set(this.model, 'leadercode', selectionRow.usercode)
    },
    /** 打开参与人姓名参照 */
    openpmTeamParticipantRefDialog() {
      // if (!this.model.milepostid) {
      //     this.$message({
      //         message: '请先选择里程碑！',
      //         type: 'warning'
      //     })
      //     this.$refs.pmTeamParticipantRef.visible = false
      // }
      if (!this.model.leadername) {
        this.$message({
          message: '请先选择负责人信息！',
          type: 'warning'
        })
        this.$refs.pmTeamParticipantRef.visible = false
      } else {
        this.$refs.pmTeamParticipantRef.visible = true
      }
    },
    /** 获取参与人姓名参数数据 */
    getpmTeamParticipantRefData(selectedRows, selectedKeys, selectedValues) {
      let participantnames = ''
      let participantcodes = ''
      for (let { username, usercode } of selectedRows) {
        participantnames = participantnames + username + ','
        participantcodes = participantcodes + usercode + ','
      }
      if (participantnames.length > 0) {
        participantnames = participantnames.substring(0, participantnames.length - 1)
        participantcodes = participantcodes.substring(0, participantcodes.length - 1)
      }
      this.$set(this.model, 'participantnames', participantnames)
      this.$set(this.model, 'participantcodes', participantcodes)
    },
    /** 提交前执行 */
    beforeSubmit() {
      const { taskcategory, starttime, endtime, planstarttime, planendtime, actualstarttime, actualendtime } = this.model
      if (taskcategory === '1') {
        this.$set(this.model, 'taskstate', '1')
        this.$set(this.model, 'progress', '0')
        this.$set(this.model, 'progressexplain', '')
        this.$set(this.model, 'actualstarttime', '')
        this.$set(this.model, 'actualendtime', '')
        if (starttime > endtime) {
          this.$tap.alert('任务计划结束日期不能早于任务计划开始日期！', 'warning')
          return false
        }
        if (
          this.$tap.date.formatDate(new Date(starttime), 'yyyy-MM-dd') <
          this.$tap.date.formatDate(new Date(planstarttime), 'yyyy-MM-dd')
        ) {
          this.$tap.alert('任务计划开始日期不能早于项目计划开工日期！', 'warning')
          return false
        }
        if (
          this.$tap.date.formatDate(new Date(endtime), 'yyyy-MM-dd') >
          this.$tap.date.formatDate(new Date(planendtime), 'yyyy-MM-dd')
        ) {
          this.$tap.alert('任务计划结束日期不能晚于项目计划完工日期！', 'warning')
          return false
        }
      }
      if (taskcategory === '2') {
        this.$set(this.model, 'taskstate', '4')
        // 默认赋值，避免统计数据异常
        this.$set(this.model, 'starttime', this.model.actualstarttime)
        this.$set(this.model, 'endtime', this.model.actualendtime)
        if (actualstarttime > actualendtime) {
          this.$tap.alert('任务实际结束日期不能早于实际开始日期！', 'warning')
          return false
        }
        if (
          this.$tap.date.formatDate(new Date(actualendtime), 'yyyy-MM-dd') >
          this.$tap.date.formatDate(new Date(), 'yyyy-MM-dd')
        ) {
          this.$tap.alert('补录任务实际结束日期不能晚于今天（' + this.$tap.date.formatDate(new Date(), 'yyyy-MM-dd') + '）！', 'warning')
          return false
        }
        if (
          this.$tap.date.formatDate(new Date(actualstarttime), 'yyyy-MM-dd') <
          this.$tap.date.formatDate(new Date(planstarttime), 'yyyy-MM-dd')
        ) {
          this.$tap.alert('任务实际开始日期不能早于项目计划开工日期！', 'warning')
          return false
        }
        if (
          this.$tap.date.formatDate(new Date(actualendtime), 'yyyy-MM-dd') >
          this.$tap.date.formatDate(new Date(planendtime), 'yyyy-MM-dd')
        ) {
          this.$tap.alert('任务实际结束日期不能晚于项目计划完工日期！', 'warning')
          return false
        }
      }
      return true
    }
  }
}
</script>

